<template>
  <div class="order-procure-edit-logis">
    <div class="info">
      <div>
        <div class="left">
          <p class="f18" style="color: #131414">修改物流</p>
        </div>
        <div class="right">
          <!-- <el-button type="info" plain @click="$router.go(-1)">返回</el-button> -->
        </div>
      </div>
    </div>

    <el-container class="content">
      <el-aside>
        <!-- 商品列表 -->
        <div class="products-list">
          <el-table class="jzt-table" :data="list" stripe style="width: 100%">
            <el-table-column prop="date" show-overflow-tooltip label="商品信息" width="400">
              <template #default="scope">
                <span>{{ scope.row.productAliasName || "-" }}</span>
              </template>
            </el-table-column>
            <el-table-column prop="deliveryQuantity" show-overflow-tooltip label="数量" />
            <el-table-column fixed="right" show-overflow-tooltip label="状态">
              <template #default="scope">
                <span>已发货</span>
              </template>
            </el-table-column>
          </el-table>
        </div>
      </el-aside>
      <el-main width="300px">
        <!-- 配送信息-->
        <div class="ps-info">
          <h3>配送信息</h3>
          <div class="mb20">
            <p>姓名：</p>
            <b>{{ detail.receivingName || "-" }}</b>
          </div>
          <div class="mb20">
            <p>电话：</p>
            <b>{{ detail.receivingMobile || "-" }}</b>
          </div>
          <div>
            <p>收货地址：</p>
            <b>{{ detail.receivingAddress || "-" }}</b>
          </div>
        </div>
        <el-divider />
        <!-- 物流信息 -->
        <div class="supper">
          <h3>物流信息</h3>
          <el-form :model="postForm" ref="postFormRef" label-width="auto" style="max-width: 600px">
            <el-form-item
              label="快递公司"
              prop="logisticsCompanyNo"
              :rules="[{ required: true, message: '请选择', trigger: ['blur'] }]"
            >
              <el-select v-model="postForm.logisticsCompanyNo" filterable placeholder="请选择" clearable @change="changeExpress">
                <el-option v-for="item in expressList" :key="item.comNo" :label="item.comName" :value="item.comNo" />
              </el-select>
            </el-form-item>
            <el-form-item
              label="物流单号"
              prop="logisticsTrackNo"
              :rules="[{ required: true, message: '请选择', trigger: ['blur'] }]"
            >
              <el-input v-model="postForm.logisticsTrackNo" placeholder="请输入"></el-input>
            </el-form-item>
            <el-form-item label="附件" prop="picIdLen">
              <!-- :rules="[
                { required: true, message: '请上传附件', trigger: ['blur', 'change'] },
                { validator: picIdLenValidator, trigger: ['blur', 'change'] }
              ]" -->
              <div style="width: 100%">
                <el-input v-model="postForm.picIdLen" v-show="false"></el-input>
                <!-- 上传图片 -->
                <el-upload
                  class="upload-demo upload-card"
                  v-model:file-list="imgFileList"
                  ref="uploadImg"
                  :show-file-list="true"
                  multiple
                  :limit="10"
                  list-type="text"
                  :auto-upload="false"
                  :on-change="
                    (file, fileList) => {
                      handleAvatarChangeIcon(file, fileList);
                    }
                  "
                  :on-preview="
                    file => {
                      reviewFile(file);
                    }
                  "
                >
                  <template #trigger>
                    <el-button class="upload-btn" :disabled="FileList.length >= 10" style="color: #86909c">
                      <el-icon class="f24"><Plus /></el-icon>
                      <p class="f12">点击上传</p>
                    </el-button>
                  </template>
                  <template #tip>
                    <p class="f12 mt10" style="color: #86909c">支持doc/docx/pdf/jpg/png，最多上传10个。</p>
                  </template>
                </el-upload>
              </div>
            </el-form-item>
          </el-form>
        </div>

        <div class="action-wrap">
          <el-button class="jzt-button" type="info" plain @click="$router.go(-1)">取消</el-button>
          <el-button type="primary" :disabled="!imgIsReady" @click="submitSend">确认修改</el-button>
        </div>
      </el-main>
    </el-container>

    <!-- 图片文件预览 -->
    <el-dialog v-model="dialogVisibleImg" title="图片文件预览" width="500">
      <img :src="reviewImgUrl" alt="" style="width: 100%" />
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="dialogVisibleImg = false">关闭</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, nextTick, onMounted, watch } from "vue";
import SearchForm from "@/components/SearchForm";
import { Search, RefreshRight } from "@element-plus/icons-vue";
import { packageInfo, selectCompanyPage, modifyLogistics } from "@/apis/order/procure";
import { useRoute, useRouter } from "vue-router";
const route = useRoute();
const router = useRouter();
import { ElMessage } from "element-plus";

const packageId = ref(route.query.packageId);
const list = ref([]);
const selectList = ref([]); //选中的行
const detail = ref({});
const expressList = ref([]); //快递公司下拉数据
const postForm = ref({ picIdLen: 0 }); //物流信息
const postFormRef = ref();
const FileList = ref([]); //商品图片list
const picIdLenValidator = (rule, value, callback) => {
  if (value > 0) {
    callback();
  } else {
    callback("请上传商品图片");
  }
};
const dialogVisibleImg = ref(false);
const reviewImgUrl = ref("");

onMounted(async () => {
  await selectCompanyPageFun();
  getList();
});

watch(
  () => FileList.value,
  val => {
    // console.log("文件长度变化了===", val);
    postForm.value.picIdLen = val.length;
  },
  { deep: true }
);

const reviewFile = file => {
  const fileArr = ["doc", "docx", "pdf"];
  const fileSuffix = file.name?.split(".")[file.name?.split(".").length - 1] || "";
  const type = fileArr.includes(fileSuffix.toLowerCase()) ? "file" : "img";
  console.log("这个文件是==", type);
  if (type === "file") {
    // 文件下载
    downloadFile(file.fileUrl || "");
  } else if (type === "img") {
    // 图片预览
    reviewImgUrl.value = file.fileUrl;
    dialogVisibleImg.value = true;
  }
};
/**
 * 下载附件
 */
const downloadFile = url => {
  console.log("这是下载附件操作", url);
  if (!url) return;
  const urlSplit = url ? url.split("/") : [];
  const name = decodeURIComponent(urlSplit[urlSplit.length - 1]);
  let xhr = new XMLHttpRequest();
  xhr.open("get", url, true);
  xhr.responseType = "blob";
  xhr.onload = function (e) {
    if (xhr.status === 200) {
      let file = xhr.response;
      let fileName = name;
      if ("msSaveOrOpenBlob" in navigator) {
        window.navigator.msSaveOrOpenBlob(file, fileName);
      } else {
        let fileUrl = window.URL.createObjectURL(file);
        let a = document.createElement("a");
        a.download = fileName;
        a.href = fileUrl;
        document.getElementsByTagName("body")[0].appendChild(a);
        a.click();
        a.parentNode.removeChild(a);
        window.URL.revokeObjectURL(fileUrl);
      }
    }
  };
  xhr.send();
};

//确认修改物流
const submitSend = () => {
  postFormRef.value.validate((valid, fields) => {
    if (valid) {
      const _detail = JSON.parse(JSON.stringify(detail.value));
      delete _detail.purchaseOrderDetails;
      const params = {
        packageId: packageId.value,
        ...postForm.value,
        attachmentFileUrls: FileList.value.map(item => item.fileUrl).join(",")
      };
      console.log("修改物流数据", params);
      modifyLogistics(params).then(res => {
        if (res.code === 200) {
          ElMessage({
            message: "物流修改成功",
            type: "success"
          });
          getList();
          // router.go(-1);
        }
      });
    } else {
      console.log("error submit!", fields);
    }
  });
};

const selectCompanyPageFun = async () => {
  const res = await selectCompanyPage({ page: 1, size: 3000 });
  expressList.value = res.data.records;

  // postForm.value.logisticsCompanyNo = "yuantong";
};

//查询清单列表数据
const getList = () => {
  packageInfo({ packageId: packageId.value }).then(res => {
    if (res.code === 200) {
      detail.value = res.data;
      list.value = res.data.purchasePackageList;

      editReview();
      console.log("清单列表===", res.data);
    }
  });
};

//物流信息数据回填
const editReview = () => {
  postForm.value.logisticsCompanyNo = detail.value.logisticsCompanyNo;
  postForm.value.logisticsCompanyName = detail.value.logisticsCompanyName;
  postForm.value.logisticsTrackNo = detail.value.logisticsTrackNo;

  const imgList = [];
  const arr = detail.value.attachmentFileUrls.split(",");
  for (let index in arr) {
    imgList.push({
      fileUrl: arr[index],
      img: arr[index],
      uid: arr[index],
      name: decodeURIComponent(arr[index].split("/")[arr[index].split("/").length - 1])
    });
  }
  imgFileList.value = imgList;
  FileList.value = imgList;
  postForm.value.picIdLen = imgFileList.value.length;
};

//更改快递公司
const changeExpress = val => {
  const obj = expressList.value.find(item => item.comNo === val);
  postForm.value.logisticsCompanyName = obj.comName;
};

//====================================图片上传========================================================================================
import useMultipartOssStore from "@/store/modules/multipartOssStore.js";
const ossStore = useMultipartOssStore();
import {
  getFolder,
  _debounce //防抖，多次频繁触发时，只执行最后一次
} from "@/utils/index";
import { imgsUpload } from "@/apis/products/specifications";
const uploadImg = ref();
const imgFileList = ref([]); //编辑时商品图片list
const imgIsReady = ref(true);
const handleAvatarChangeIcon = _debounce(async (file, fileList, type = "img-word") => {
  //选中文件触发的change事件
  console.log("触发文件上传==", fileList);
  let _fileList = fileList.filter(item => item.status === "ready"); //未上传成功的图片
  const flag = await fileType(type, type === "img-word" ? _fileList : [file]);
  if (!flag) {
    if (type === "img-word") {
      ElMessage({
        message: "支持扩展名：doc/docx/pdf/jpg",
        type: "error",
        offset: 60
      });
      const errorFile = _fileList.filter(
        item =>
          !(
            item.raw.type === "image/jpeg" ||
            item.raw.type === "image/png" ||
            item.raw.type === "application/msword" ||
            item.raw.type === "application/vnd.openxmlformats-officedocument.wordprocessingml.document" ||
            item.raw.type === "application/pdf"
          )
      );
      for (let item of errorFile) {
        uploadImg.value.handleRemove(item);
      }
    }
    return;
  }
  if (type === "img-word") {
    FileList.value = fileList;
    imgIsReady.value = false;
    for (let item of _fileList) {
      await customUpload(item, { file: item }, type);
    }
    imgIsReady.value = true;
  }
}, 100);
/**
 * 校验文件类型
 */
const fileType = async (type, fileList) => {
  let flag = true;
  if (type === "img") {
    for (let item of fileList) {
      if (!(item.raw.type === "image/jpeg" || item.raw.type === "image/png")) {
        flag = false;
      }
    }
  } else if (type === "img-word") {
    for (let item of fileList) {
      if (
        !(
          item.raw.type === "image/jpeg" ||
          item.raw.type === "image/png" ||
          item.raw.type === "application/msword" ||
          item.raw.type === "application/vnd.openxmlformats-officedocument.wordprocessingml.document" ||
          item.raw.type === "application/pdf"
        )
      ) {
        flag = false;
      }
    }
  }
  return flag;
};
/**
 * 上传
 */
const getFileName = name => {
  const arr = name.split(".");
  const _arr = JSON.parse(JSON.stringify(arr));
  let _name = "";
  let _suffix = "";
  if (arr.length > 2) {
    _arr.splice(_arr.length - 1, 1);
    _name = _arr.join(".");
    _suffix = arr[arr.length - 1];
  } else {
    _name = arr[0];
    _suffix = arr[1];
  }
  const folder = getFolder();
  return folder + _name + new Date().getTime() + "." + _suffix;
};
const customUpload = async (item, option, type) => {
  // 合并已上传和当前上传文件
  const objName = getFileName(option.file.name);
  await ossStore
    .submit(objName, option.file.raw)
    .then(async res => {
      await ossStore.setACL(objName, fileReadRole.publicRead);
      res.fileUrl = await ossStore.signatureUrl(objName);
      console.log("文件上传成功，地址为===", res.fileUrl.split("?")[0]);
      if (type === "img-word") {
        item["fileUrl"] = res.fileUrl.split("?")[0];
      }
      item["folder"] = objName;

      const Option = JSON.parse(JSON.stringify(option));
      uploadIMG(Option); //图片上传到业务端
    })
    .catch(err => {
      alert(JSON.stringify(err));
    });
};

//将图片上传到业务端服务
const uploadIMG = option => {
  const nameArr = option.file.name.split(".");
  const uploadArr = [
    {
      fileId: option.file.uid,
      objectName: option.file.folder, //目录＋文件名称
      url: option.file.img || option.file.video,
      access: "public-read",
      fileName: option.file.name, //文件名称
      bucketName: "51-jzt-dev",
      size: option.file.size,
      type: true,
      suffix: nameArr[nameArr.length - 1]
    }
  ];
  imgsUpload(uploadArr).then(res => {
    console.log(909090, res);
  });
};
const fileReadRole = {
  defaultRole: "",
  privateRole: "private",
  publicRead: "public-read",
  publicReadWrite: "public-read-write"
};
</script>

<style lang="scss" scoped>
:deep(.upload-btn.el-button > span) {
  display: block;
}
:deep(.upload-card) {
  .el-upload-list__item.is-ready,
  .el-upload-list__item.is-success {
    width: 100% !important;
    height: auto !important;
  }
}
:deep(.el-icon--close-tip) {
  display: none !important;
}
.order-procure-edit-logis {
  height: calc(100% - 0px);
  overflow-y: auto;
  padding: 0 20px 0px 20px;
  position: relative;

  .search-wrap {
    padding: 20px;
    overflow-x: hidden;
    background-color: #f6f8fa;
  }

  .info {
    position: sticky;
    top: 0;
    background-color: white;
    z-index: 22;
    & > div {
      display: flex;
      justify-content: space-between;
      align-items: center;
      padding: 14px 0;
      border-bottom: 1px solid #e2e8f0;
    }
    & > div > div {
      display: flex;
    }
    .left {
      .creater {
        color: #1a1a1a;
        font-weight: bold;
      }
    }
  }
  .content {
    height: calc(100% - 61px);
    :deep(.el-aside) {
      flex: 1;
      padding: 20px 20px 20px 0;
      header {
        display: flex;
        justify-content: space-between;
        margin-bottom: 18px;
        .supper {
          flex: 1;
          display: flex;
          align-items: center;
          padding-right: 20px;
          p {
            width: 52px;
          }
          .el-select {
            flex: 1;
          }
        }
      }
      .products-list {
        .col1 {
          & > div {
            display: flex;
          }

          .left {
            img {
              width: 80px;
              height: 80px;
              border-radius: 4px;
            }
          }
          .right {
            padding-left: 18px;
            .name {
              font-size: 14px;
              color: #3d3d3d;
              margin-bottom: 5px;
            }
            p {
              font-size: 12px;
              color: #86909c;
              margin-bottom: 5px;
            }
          }
        }
      }
    }
    :deep(.el-main) {
      width: 300px;
      flex: none;
      background-color: white;
      border-left: 1px solid #e2e8f0;
      padding-bottom: 64px;
      .sh-store {
        display: flex;
        align-items: center;
        p {
          width: 66px;
        }
        .el-select {
          flex: 1;
        }
      }
      h3 {
        color: #86909c;
        font-weight: normal;
        margin: 0 0 16px 0;
      }
      .ps-info {
        p {
          color: #86909c;
          margin-bottom: 10px;
        }
        b {
          font-weight: normal;
          color: #1a1a1a;
          line-height: 20px;
        }
      }
      .rk-tips {
        p {
          color: #4e5969;
          margin-bottom: 16px;
        }
      }
      .supper {
        .el-form {
          .el-form-item {
            display: block;
            .el-form-item__label-wrap {
              margin-left: 0 !important;
            }
            .el-button {
              width: 100%;
              height: 100%;
            }
          }
        }
        .el-upload.el-upload--text {
          width: 80px;
          height: 80px;
          background-color: #f2f3f5;
          border-radius: 4px;
        }
        .el-upload-list__item.is-ready {
          width: auto;
          height: auto;
        }
      }
    }
  }
  .action-wrap {
    position: absolute;
    bottom: 0;
    right: 0;
    width: 319px;
    height: 64px;
    background-color: white;
    display: flex;
    align-items: center;
    justify-content: center;
    padding: 0 20px;
    box-shadow: 0px -3px 10px 0px rgba(4, 24, 48, 0.1);
    box-sizing: border-box;
  }
}
</style>
